<template>
  <div class='container'>
      <el-card style="margin: 20px 10px">
        <!-- 新增试题 -->
        <el-row
        type="flex"
        justify="center"
        align="middle">
          <el-col style="color: #efb43c; font-size: 15px">
            说明: 目前支持学科条件筛选
          </el-col>
          <el-col>
            <el-row
              type="flex"
              justify="end">
              <el-button type="success" icon="el-icon-edit" size="small" @click="$router.push('/questions/new')">新增试题</el-button>
            <el-row>
          </el-col>
        </el-row>

        <!-- 表单 搜索条件 -->
        <el-form
        :model="formData"
        style="margin-top: 20px"
        label-width="70px"
        size="mini">
          <el-row>
            <el-col :span="6">
              <el-form-item label="学科" >
                <el-select v-model="formData.subjectID" placeholder="请选择">
                  <el-option v-for="subject in subjectList" :key="subject.value" :label="subject.label" :value="subject.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二级目录" >
                <el-select v-model="formData.catalogID" placeholder="请选择">
                  <el-option v-for="catalog in catalogList" :key="catalog.id" :label="catalog.directoryName" :value="catalog.id"></el-option>
                </el-select>
              </el-form-item>
           </el-col>
           <el-col :span="6">
              <el-form-item label="标签" >
                <el-select v-model="formData.tags" placeholder="请选择">
                  <el-option v-for="tag in tagList" :key="tag.id" :label="tag.tagName" :value="tag.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关键字" >
                <el-input v-model="formData.keyword" placeholder="请输入题干关键字">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="试题类型" >
                <el-select v-model="formData.questionType" placeholder="请选择">
                  <el-option v-for="type in questionType" :key="type.value" :label="type.label" :value="type.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="难度" >
                <el-select v-model="formData.difficulty" placeholder="请选择">
                  <el-option v-for="type in difficulty" :key="type.value" :label="type.label" :value="type.value"></el-option>
                </el-select>
              </el-form-item>
           </el-col>
           <el-col :span="6">
              <el-form-item label="方向" >
                <el-select v-model="formData.direction" placeholder="请选择">
                  <el-option v-for="(item, i) in direction" :key="i" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="录入人" >
                <el-select v-model="formData.creatorID" placeholder="请选择">
                  <el-option v-for="user in userList" :key="user.id" :label="user.username" :value="user.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="题目备注" >
                <el-input v-model="formData.remarks">
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称" >
                <el-input v-model="formData.shortName">
              </el-form-item>
           </el-col>
           <el-col :span="6">
              <el-form-item label="城市" >
                <el-row
                type="flex"
                justify="center">
                  <el-select v-model="formData.province" placeholder="请选择" @change="provinceChange">
                    <el-option v-for="(item, i) in provinceList" :key="i" :label="item" :value="item"></el-option>
                  </el-select>
                  <el-select v-model="formData.city" placeholder="请选择">
                  <el-option v-for="(item, i) in cityList" :key="i" :label="item" :value="item"></el-option>
                  </el-select>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-row
              type="flex"
              justify="end">
                <el-button size="mini" @click="clear">清除</el-button>
                <el-button size="mini" type="primary" @click="search">搜素</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>

        <!-- 提示信息 查询结果总数 -->
          <el-alert
            :title="'共'+page.total+'条'"
            type="info"
            show-icon
            :closable="false"
            style="margin-top: 10px">
          </el-alert>

        <!-- 查询结果表格 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%; margin-top: 20px"
          :header-cell-style="{background:'#fafafa'}">
          <el-table-column
            prop="number"
            label="试题编号"
            width="150">
          </el-table-column>
          <el-table-column
            prop="subjectID"
            :formatter="formatSubject"
            label="学科"
            width="100">
          </el-table-column>
          <el-table-column
            prop="catalogID"
            :formatter="formatCatalog"
            label="目录"
            width="100">
          </el-table-column>
          <el-table-column
            prop="questionType"
            :formatter="formatQuestionType"
            label="题型"
            width="80">
          </el-table-column>
          <el-table-column
            prop="question"
            label="题干"
            width="200">
            <!-- 作用域插槽 格式化题干去除标签 -->
            <template slot-scope="{ row }">
              <span v-html="row.question"></span>
            </template>
          </el-table-column>
          <el-table-column
            prop="addDate"
            label="录入时间"
            width="150">
            <!-- 作用域插槽 过滤器格式化时间 -->
            <template slot-scope="{ row }">
              {{row.addDate | formatDate}}
            </template>
          </el-table-column>
          <el-table-column
            prop="difficulty"
            :formatter="formatDifficulty"
            label="难度"
            width="100">
          </el-table-column>
          <el-table-column
            prop="creator"
            label="录入人"
            width="130">
          </el-table-column>
          <el-table-column
            label="操作"
            width="180">
            <!-- 作用域插槽 操作每条数据 -->
            <template slot-scope="{ row }">
              <el-tooltip content="预览" placement="bottom" effect="light" :open-delay="1000">
                <el-button type="primary" plain icon="el-icon-view" circle  size="small" @click="showViewBtn(row)"></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="bottom" effect="light" :open-delay="1000">
              <el-button type="success" plain icon="el-icon-edit" circle  size="small" @click="$router.push(`/questions/new?id=${row.id}`)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="bottom" effect="light" :open-delay="1000">
              <el-button type="danger" plain icon="el-icon-delete" circle size="small" @click="deleteBtn(row.id)"></el-button>
              </el-tooltip>
              <el-tooltip content="加入精选" placement="bottom" effect="light" :open-delay="1000">
              <el-button type="warning" plain icon="el-icon-check" circle size="small" @click="addChoiceBtn(row.id)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="end"
          style="margin-top: 20px"
          >
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.page"
            :page-sizes="[2, 5, 10, 20, 50]"
            :page-size="page.pagesize"
            :total="page.total"
            layout="prev, pager, next, sizes, jumper"
            background
            >
          </el-pagination>
        </el-row>
      </el-card>

      <!-- 题目预览 -->
      <el-dialog title="题目预览" :visible="showViewDialog" width="700px" @close="closeDialog">
        <el-row type="flex" style="margin-bottom: 15px">
          <el-col :span="6">【题型】：{{currentQuestion.questionType}}</el-col>
          <el-col :span="6">【编号】：{{currentQuestion.id}}</el-col>
          <el-col :span="6">【难度】：{{currentQuestion.difficulty}}</el-col>
          <el-col :span="6">【标签】：{{currentQuestion.tags}}</el-col>
        </el-row>
        <el-row type="flex" style="margin-bottom: 15px">
          <el-col :span="6">【学科】：{{currentQuestion.subjectID}}</el-col>
          <el-col :span="6">【目录】：{{currentQuestion.catalogID}}</el-col>
          <el-col :span="6">【方向】：{{currentQuestion.direction}}</el-col>
        </el-row>
        <div class="splitLine"></div>
        <el-row>
          【题干】：
        </el-row>
        <el-row v-html="currentQuestion.question" style="color: #e6a23c"></el-row>
        <!-- 试题选项 -->
        <!-- 单选 -->
        <template v-if="currentQuestion.questionType === '单选'">
          <el-radio
            v-for="option in currentQuestion.options"
            :key="option.id"
            v-model="option.isRight"
            :label="1">
            {{option.code + '. ' + option.title}}
          </el-radio>
        </template>
        <!-- 多选 -->
        <template v-if="currentQuestion.questionType === '多选'">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="option in currentQuestion.options"
            :key="option.id"
            :label="option.isRight">
            {{option.code + '. ' + option.title}}
          </el-checkbox>
        </el-checkbox-group>
        </template>
        <div class="splitLine"></div>
        <el-row style="margin-bottom: 15px">
          【参考答案】：
          <el-button type="danger" size="mini" @click="showVideo = true">视频答案预览</el-button>
          <div class="video" v-if="showVideo">
            <video width="320" height="240" controls autoplay muted :src="currentQuestion.videoURL">
                <!-- bug: 视频不能正常播放 无法访问视频地址 -->
                您的浏览器不支持 video 标签
            </video>
          </div>
        </el-row>
        <div class="splitLine"></div>
        <el-row>
          【答案解析】：
          <span v-html="currentQuestion.answer"></span>
        </el-row>
        <div class="splitLine"></div>
        <el-row>
          【题目备注】：
          <span v-html="currentQuestion.remarks"></span>
        </el-row>
        <!-- 关闭按钮 -->
        <template slot="footer">
          <el-row type="flex" justify="end">
            <el-col>
              <el-button type="primary" size="small" @click="closeDialog">关闭</el-button>
            </el-col>
          </el-row>
        </template>
      </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/directorys'
import { list as tagList } from '@/api/hmmm/tags'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { list as userList } from '@/api/base/users'
import { provinces, citys } from '@/api/hmmm/citys'
import { list as questionList, detail, remove, choiceAdd } from '@/api/hmmm/questions'
export default {
  // 组件名称
  name: 'Questions',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
    return {
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 二级目录 待定
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 省份
        city: '' // 城市
      },
      subjectList: [], // 学科列表
      catalogList: [], // 目录列表
      tagList: [], // 标签列表
      questionType, // 试题类型
      difficulty, // 难度
      direction, // 方向
      userList: [], // 录入人列表
      provinceList: provinces, // 城市列表
      cityList: [], // 地区列表
      // 表格数据
      tableData: [],
      // 分页数据
      page: {
        page: 1, // 当前页码
        pagesize: 2, // 页大小
        total: 0 // 基础题库的试题总数
      },
      showViewDialog: false, // 预览对话框
      currentQuestion: {}, // 预览的试题详情
      checkList: [1], // 多选题的选中项
      showVideo: false, // 视频答案预览
      isFilterSearch: false, // 当前是否为条件筛选状态
      loading: false // 数据加载状态,
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
  */
  async created () {
    await this.simple()
    await this.list()
    await this.tags()
    await this.users()

    this.questions()
  },
  /**
  * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
  */
  mounted () {},
  // 组件方法
  methods: {
    // 学科简单列表
    async simple () {
      const { data } = await simple()
      this.subjectList = data
    },
    // 目录列表
    async list () {
      const { data: { counts } } = await list()
      const { data: { items } } = await list({ pagesize: counts })
      this.catalogList = items
    },
    // 标签列表
    async tags () {
      const { data: { counts } } = await tagList()
      const { data: { items } } = await tagList({ pagesize: counts })
      this.tagList = items
    },
    // 录入人列表
    async users () {
      const { data: { counts } } = await userList()
      const { data: { list } } = await userList({ pagesize: counts })
      this.userList = list
    },
    // 选择城市和地区
    provinceChange (value) {
      this.formData.city = ''
      this.cityList = citys(value)
    },
    // 重置表单 和 筛选状态
    clear () {
      this.formData = {
        subjectID: '', // 学科
        catalogID: '', // 二级目录 待定
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        province: '', // 省份
        city: '' // 城市
      }
      this.isFilterSearch = false
    },
    // 获取基础题库列表
    async questions () {
      this.loading = true
      const { data: { items, counts } } = await questionList(this.page)
      this.tableData = items
      this.page.total = counts
      this.loading = false
    },
    // 搜索功能
    async search () {
      this.loading = true
      if (!this.formData.subjectID) {
        return this.questions()
      }
      const { data: { items, counts } } = await questionList({ ...this.formData, ...this.page })
      this.isFilterSearch = true // 当前处于条件筛选状态
      this.tableData = items
      this.page.total = counts
      this.loading = false
    },
    // 学科的数据格式化
    formatSubject (row, column, cellValue, index) {
      const obj = this.subjectList.find(item => item.value === cellValue)
      return obj.label
    },
    // 目录的数据格式化
    formatCatalog (row, column, cellValue, index) {
      const obj = this.catalogList.find(item => item.id === cellValue)
      return obj.directoryName
    },
    // 试题类型的数据格式化
    formatQuestionType (row, column, cellValue, index) {
      const obj = this.questionType.find(item => item.value === cellValue)
      return obj.label
    },
    // 难度的数据格式化
    formatDifficulty (row, column, cellValue, index) {
      const obj = this.difficulty.find(item => item.value === cellValue)
      return obj.label
    },
    // 点击预览 - 题目预览对话框
    async showViewBtn (row) {
      const { data } = await detail({ id: row.id })
      this.currentQuestion = data
      this.currentQuestion.questionType = this.formatQuestionType(null, null, this.currentQuestion.questionType, null)
      this.currentQuestion.subjectID = this.formatSubject(null, null, this.currentQuestion.subjectID, null)
      this.currentQuestion.difficulty = this.formatDifficulty(null, null, this.currentQuestion.difficulty, null)
      this.currentQuestion.catalogID = this.formatCatalog(null, null, this.currentQuestion.catalogID, null)
      this.showViewDialog = true
    },
    // 关闭题目预览对话框
    closeDialog () {
      this.showViewDialog = false
    },
    // 删除试题
    deleteBtn (id) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove({ id })
        await this.questions()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 加入精选题库
    addChoiceBtn (id) {
      this.$confirm('确定将该题目加入精选吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        await choiceAdd({ id, choiceState: 1 })
        await this.questions()
        this.$message({
          type: 'success',
          message: '已加入精选!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加'
        })
      })
    },
    // 分页组件中,改变页面大小
    async handleSizeChange (val) {
      this.page.pagesize = val
      // 如果当前为条件筛选状态, 切换页码或页面大小,应执行含条件筛选的获取基础题库列表
      if (this.isFilterSearch) {
        return await this.search()
      }
      await this.questions()
    },
    // 分页组件中,改变当前页码
    async handleCurrentChange (val) {
      this.page.page = val
      if (this.isFilterSearch) {
        return await this.search()
      }
      await this.questions()
    }
  }
}
</script>

<style scoped>
.splitLine {
  margin-bottom: 10px;
  font-weight: 700;
  border-bottom: 2px solid #c0c4cc;
}
.el-radio, .el-checkbox{
  display: block;
  margin:10px 0;
  pointer-events: none;
}
</style>
